var express = require('express');
var router = express.Router();
var request = require('request');
var querystring = require('querystring');
var multiparty = require('multiparty');
// 安装依赖包
// npm install @alicloud/imagerecog20190930
const ImagerecogClient = require('@alicloud/imagerecog20190930');
const OpenapiClient = require('@alicloud/openapi-client');
const TeaUtil = require('@alicloud/tea-util');
const fs = require("fs");
const util = require("util");
const http = require('http');
const https = require('https');
const { parse } = require('../imgtobase64')
const { devicesModel, deviceAdminModel, device_kindModel } = require('../model/zhy_model')


router.get('/getdata', async (req, res) => {
	res.send({ data: 123 })
})
router.post('/send', (req, res) => {
	let body = req.body.imageURL
	let config = new OpenapiClient.Config({
		// 创建AccessKey ID和AccessKey Secret，请参考https://help.aliyun.com/document_detail/175144.html。
		// 如果您用的是RAM用户AccessKey，还需要为RAM用户授予权限AliyunVIAPIFullAccess，请参考https://help.aliyun.com/document_detail/145025.html。
		// 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行示例前必须先配置环境变量。 
		accessKeyId: "LTAI5t6eRJYzS7RKk8U5MajB",
		accessKeySecret: "U78LPuBsdHZv3wNzwiqgVx52EzoMez"
	});
	// 访问的域名
	config.endpoint = `imagerecog.cn-shanghai.aliyuncs.com`;
	const client = new ImagerecogClient.default(config);
	const getResponse = function (httpClient, url) {
		return new Promise((resolve, reject) => {
			httpClient.get(url, function (response) {
				resolve(response);
			})
		})
	}
	const request = async function () {
		try {
			const client = new ImagerecogClient.default(config);
			let classifyingRubbishAdvanceRequest = new ImagerecogClient.ClassifyingRubbishAdvanceRequest();
			// 场景一，使用本地文件
			// const fileStream = fs.createReadStream('/tmp/ClassifyingRubbish1.jpg');
			// classifyingRubbishAdvanceRequest.imageURLObject = fileStream;
			// 场景二，使用任意可访问的url
			const url = new URL(body);
			console.log(url)
			const httpClient = (url.protocol == "https:") ? https : http;
			classifyingRubbishAdvanceRequest.imageURLObject = await getResponse(httpClient, url);
			let runtime = new TeaUtil.RuntimeOptions({});
			client.classifyingRubbishAdvance(classifyingRubbishAdvanceRequest, runtime)
				.then(function (classifyingRubbishResponse) {
					// 获取整体结果
					// console.log(classifyingRubbishResponse);
					// 获取单个字段
					res.json({
						code: 200,
						data: classifyingRubbishResponse.body.data
					})

				}, function (error) {
					// 获取整体报错信息
					console.log(error);
					// 获取单个字段
					console.log(error.data.Code);
				})
		} catch (error) {
			console.log(error);
		}
	}();
})
router.post('/upload', (req, res) => {
	let form = new multiparty.Form();
	form.uploadDir = 'upload'   //上传图片保存的地址     目录必须存在
	form.parse(req, function (err, fields, files) {
		//获取提交的数据以及图片上传成功返回的图片信息
		console.log(fields);  /*获取表单的数据*/
		console.log(files);  /*图片上传成功返回的信息*/
		let file = files.file[0].path
		res.send(
			"http://127.0.0.1:7890/" + file.replace('\\', "\/")
		);

	});

})

router.post('/relation', async (req, resq) => {
	let img = req.body.img
	http.get(img, function (res) {
		var chunks = [];
		var size = 0;
		res.on('data', function (chunk) {
			chunks.push(chunk);
			size += chunk.length;　　//累加缓冲数据的长度
		});
		res.on('end', async function (err) {
			var data = Buffer.concat(chunks, size);
			var base64Img = data.toString('base64');
			var url = "http://api.tianapi.com/txapi/imglajifenlei/";
			var requestData = querystring.stringify({
				"key": "e1f4d6d56e47bef0bdee03009e7c1549",
				"img": `data:image/png;base64,${base64Img}`,
			});

			httprequest(url, requestData);
			 function httprequest(url, data) {
				 request({
					url: url,
					method: "POST",
					headers: {
						"content-type": "application/x-www-form-urlencoded",
					},
					body: data
				}, function (error, response, body) {
					if (!error && response.statusCode == 200) {	
						console.log(body)	
						resq.send({
							code:200,
							data: JSON.parse(body)
						})
					}
				});
			};
		
		});
	});
	
	
})
router.get('/devices', async (req, res) => {
	let data = await devicesModel.find().populate('deviceKinds_id')
	res.json({
		code: 200,
		data
	})
})
router.post('/applydevice', async (req, res) => {
	let body = req.body
	console.log(body)
	await deviceAdminModel.create(body)
	res.json({
		code: 200,
		msg: "申请成功"
	})
})
router.get('/deviceList', async (req, res) => {
	let data = await deviceAdminModel.find().populate('device_id')
	res.json({
		code: 200,
		data
	})
})
router.get('/exit_device/:id', async (req, res) => {
	let id = req.params.id
	let data = await deviceAdminModel.findOne({ _id: id }).populate('device_id').lean()
	let msg = await device_kindModel.findOne({ _id: data.device_id.deviceKinds_id })
	data.device_id.deviceKinds_id = msg
	res.json({
		code: 200,
		data
	})
})
router.post('/news',(req,res)=>{
	let body=req.body.word
	console.log(body)
	request.post({
   url:'https://apis.tianapi.com/lajifenlei/index',
	   form:{
			key:'e1f4d6d56e47bef0bdee03009e7c1549',word:body
   } 
   },function(err,response,tianapi_data ){
	   res.json(JSON.parse(tianapi_data))
});
})
module.exports = router;